<template>
  <div style='position: relative'>
    <!--右边主体部分-->
    <transition name='el-zoom-in-center'>
      <router-view ></router-view>
    </transition>
    <avue-crud ref="crud" :data="tableData" :option="option" v-model="obj"
               @row-del="rowDel" @row-save="handleRowSave" :page.sync="rolePage"
               @row-update="handleRowUpdate"
               @size-change="handleSizeChange"
               @current-change="handleCurrentChange"
               :cell-style="getCellStyle">
      <template slot="status"  slot-scope="scope">
        <el-tag size="mini" type="success" v-if="scope.row.status === 1">
          启用
        </el-tag>
        <el-tag size="mini" type="danger" v-if="scope.row.status === 0">
          停用
        </el-tag>
      </template>
      <template slot="menuLeft" slot-scope="scope" >
        <el-button
          v-btpermission='"角色管理-添加"'
          style="margin-left: 5px"
          type="primary"
          @click=";(adddialogVisible = true),
       (roleDto =
       {
        name: '',
        code: '',
        remark: '',
        id: '',
        status: '',
        version: '',
        created_by: '',
        companyId: '',
        tenantId: '',
        orgId: ''
      }
      )
      ,(roleDto.status = 1)"
        ><em class="el-icon-plus">增加</em></el-button>
        <el-button
          style="margin-left: 5px"
          type="primary"
          @click="($router.push({
                  path:'/centre/permission-manager/role/addRoleRouterIndex_testV1',
                  query: {
                  params: 'add_flag'
                  }
                  })),(loadingInstance = Loading().service({target:$refs.crud.$el}))"
        ><em class="el-icon-plus">增加样式2</em></el-button>
        <el-button
          v-btpermission='"角色管理-按钮（DELETE）-/v1/role/batch"'
          style="margin-left: 5px"
          type="danger"
          @click="batchRemoveRole"
        ><em class="el-icon-delete">删除</em></el-button>
        <el-button
          v-btpermission='"角色管理-按钮（POST）-/assignResource"'
          style="margin-left: 5px"
          type="primary"角色管理-删除
          @click="getResourceTree"
        ><em class="el-icon-video-play" />资源分配</el-button>
        <el-button
          v-btpermission='"角色管理-按钮（GET）-commonQueryUser"'
          style="margin-left: 5px"
          type="primary"
          @click="getUserAll"
        ><em class="el-icon-s-custom">用户分配</em></el-button>
        <el-button
          v-btpermission='"角色管理-按钮（GET）-/selectCompany"'
          style="margin-left: 5px"
          type="primary"
          @click="getCompanyAll"
        ><em class="el-icon-s-custom">公司分配</em></el-button>
        <el-button
          style="margin-left: 5px"
          type="primary"
          @click="refreshData"
        ><em class="el-icon-refresh">刷新</em></el-button>




      </template>
      <template slot="menuHeader">
        <div style="text-align: center;font-size: 14px"
        >操作</div>
      </template>
      <template slot="menu" slot-scope="scope">
        <div style='display: flex'>
          <el-button
            style="margin-left: 5px"
            size="mini"
            type="primary"
            @click="copyRole(scope.row)"
            v-btpermission='"角色管理-按钮（POST）-/v1/role/copy"'
          >复制</el-button>
          <el-button
            v-btpermission='"角色管理-修改"'
            style="margin-left: 5px"
            size="mini"
            @click.stop="handleEdit(scope.row,scope.index)"
          >编辑</el-button>
          <el-button
            v-btpermission='"角色管理-删除"'
            style="margin-left: 5px"
            size="mini"
            type="danger"
            @click="removeRole(scope.row)"
          >删除</el-button>
          <el-button
            style="margin-left: 5px"
            size="mini"
            type="warning"
            @click="permission(scope.row)"
          >查看权限</el-button>
        </div>
      </template>
    </avue-crud>
    <!--  增加的弹框&ndash;&gt;-->
    <add_role_dialog
        :caption="addTitle"
        :visible="adddialogVisible"
        :model="roleDto"
        :rules="rules"
        width="60%"
        @OkButtonClick="addRole"
        @CancelButtonClick="adddialogVisible = false">
      </add_role_dialog>
    <!--    更新的弹框-->
    <update_role_dialog
      :caption="updateTitle"
      :visible="updatedialogVisible"
      :model="roleDto"
      :rules="rules"
      width="60%"
      @OkButtonClick="updateRole"
      @CancelButtonClick="updatedialogVisible = false">
    </update_role_dialog>
    <!--用户分配的弹框-->
    <user_dialog ref = 'userTable' :username='userQuery.name' @queryUserByName='queryUserByName'>

    </user_dialog>
    <!--资源分配的弹框-->
    <resource_dialog ref = "tree"
                     :resourcedialogVisible="resourcedialogVisible"
                     :resourceData = resourceData
                     :listLoading = listLoading
                     :isReviewPerMission = this.isReviewPerMission
                     @handleClose = 'handleClose'
                     @handleNodeClick = 'handleNodeClick'
                     @assignResource = 'assignResource'
                     @CancelButtonClick="resourcedialogVisible = false"
    >
    </resource_dialog>
    <company_dialog ref='companyTable'>
    </company_dialog>

  </div>
</template>

<script>
import {
  add,
  assignResource,
  assignUser,
  batchRemove,
  commonQuery,
  commonQueryUser,
  modify,
  modifyRoleCompany,
  queryRoleById,
  queryRoleCompany,
  remove,
  selectCompany
} from '@/api/right/role'
import { commonQuery as companyQuery } from '@/api/org/company'
import { treeQuery } from '@/api/right/resource'
import add_role_dialog from '@/views/bg/role/add_role_dialog.vue'
import update_role_dialog from '@/views/bg/role/update_role_dialog.vue'
import resource_dialog from '@/views/bg/role/resource_dialog.vue'
import user_dialog from '@/views/bg/role/user_dialog.vue'
import company_dialog from '@/views/bg/role/company_dialog.vue'
import { Loading } from 'element-ui'

export default {
  watch: {
    $route: {
      handler: function(val, oldVal) {
        console.log(9802336)
        if (val.path === '/centre/permission-manager/role' && oldVal.path === '/centre/permission-manager/role/addRoleRouterIndex_testV1'){
          if (this.$route.query.params){
            let add_roleDto = JSON.parse(this.$route.query.params);
            this.addRole(add_roleDto)
          }else {
            console.log("关闭加载")
            this.loadingInstance.close();
          }

        }
      },
      // 深度观察监听
      deep: true
    },
  },
  name: 'Role',
  components:{add_role_dialog,update_role_dialog,resource_dialog,user_dialog,company_dialog},
  mounted() {
    this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
      this.loadingInstance = Loading.service({
        target:this.$refs.crud.$refs.table.$el
      });
    });
    this.fetchData(this.rolePage.pageNum)
    this.getCompany()

  },
  data: function() {
    return {
      obj:{},
      option:{
        border:true,
        title:'',
        page:'center',
        align:'center',
        menuWidth:360,
        menuAlign:'center',
        selection:true,
        index:true,
        reserveSelection:true,
        rowKey:'id',
        addBtn:false,
        refreshBtn:false,
        columnBtn:false,
        editBtn:false,
        delBtn:false,
        column:[
          {
            label:'角色',
            prop:'name',
            labelClassName:"labelClassName",

          },
          {
            label:'角色编号',
            prop:'code',
            labelClassName:"labelClassName",

          },
          {
            label:'角色备注',
            prop:'remark',
            labelClassName:"labelClassName",

          },
          {
            label: "所属公司",
            prop: "_companyDTO",
            bind:"companyDTO.name",
            slot: true,
            labelClassName:"labelClassName"

          },
          {
            label: "所属机构",
            prop: "_organizationDTO",
            bind:"organizationDTO.name",
            slot: true,
            labelClassName:"labelClassName",

          },
          {
            label: "是否启用",
            prop: "status",
            slot: true,
            labelClassName:"labelClassName",

          },

        ]
      },
      loadingInstance:{},
      test1:true,
      addTitle: '增加角色',
      updateTitle: '修改角色',
      userTitle: '用户分配',
      resourceTitle: '资源分配',
      treeData: [],
      resourceData: [],
      listLoading: false,
      tableData: [],
      userData: [],
      companyData: [],
      rolePage: {
        total: null,
        // 页号
        pageNum: 1,
        // 页大小
        pageSize: 20,
      },
      userPage: {
        total: null,
        // 页号
        pageNum: 1,
        // 页大小
        pageSize: 15,

        pages: null
      },
      roleQuery: { companyId: '' },
      userQuery: {name:''},
      roleResourceDTO: {},
      roleCompanyDTO: {
        roleIds: [],
        authCompanyIds: []
      },
      userdialogVisible: false,
      resourcedialogVisible: false,
      companydialogVisible: false,
      isReviewPerMission: false,
      adddialogVisible: false,
      updatedialogVisible: false,
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '角色编号不能为空', trigger: 'blur' }
        ],
        remark: [{ required: false, message: '备注不能为空', trigger: 'blur' }],
        companyId: [
          { required: true, message: '所属公司不能为空', trigger: 'change' }
        ]
      },
      //接收角色查询
      roleVo: {},
      //发送角色参数
      roleDto: {
        name: '',
        code: '',
        remark: '',
        id: '',
        status: '',
        version: '',
        created_by: '',
        companyId: '',
        tenantId: '',
        orgId: ''
      },
      roleIdList: [],
      userIdList: [],
      resourceIdList: [],
      selected: [], // 被选中的行
      resourcedialogType: '',
      selectionData: [], // 保存选中的id
      dialogType: ''
    }
  },
  created() {

  },
  methods: {
    Loading() {
      return Loading
    },
    test(){
      console.log("多选框",JSON.stringify(this.$refs.crud.$refs.table.selection))
    },
    getKey(row){
      return row.id;
    },
    /**
     *  it's function descritio
     *  who what time do it
     * @param list   从后端取回的树节点，他没有做任务父子节点处理
     * @returns {*[]}  不需要
     */
    transform(no_transform_tree_list) {
      let tree = []
      // 存储一级节点（系统）
      no_transform_tree_list.map((item) => {
        if (parseInt(item.parentId) === -1 && item.resourceType === 2) {
          tree.push({ label: item.name, id: item.id, children: [] })
        }
      })
      // 存储二级节点（主菜单）
      tree.map((itemParent) => {
        no_transform_tree_list.map((item) => {
          if (itemParent.id === item.parentId) {
            itemParent.children.push({
              id: item.id,
              label: item.name,
              children: []
            })
          }
        })
      })
      // 存储三级节点（子菜单）
      tree.map((itemParent) => {
        itemParent.children.map((itemSecondParent) => {
          no_transform_tree_list.map((item) => {
            if (itemSecondParent.id === item.parentId) {
              itemSecondParent.children.push({
                id: item.id,
                label: item.name,
                children: []
              })
            }
          })
        })
      })
      // 存储四级节点（请求权限）
      tree.map((itemParent) => {
        itemParent.children.map((itemSecondParent) => {
          itemSecondParent.children.map((itemthirdParent) => {
            no_transform_tree_list.map((item) => {
              if (itemthirdParent.id === item.parentId) {
                itemthirdParent.children.push({ id: item.id, label: item.name })
              }
            })
          })
        })
      })
      return tree
    },

    /**
     *  树节点默认展开事件
     */
    handleNodeClick(data) {
      // this.roleQuery.companyId = data.id
      // this.fetchData(1)
      // this.roleQuery = {}
    },
    /**
     * 分页逻辑
     *
     */
    //角色管理分页
    handleSizeChange(val) {
      this.loadingInstance = Loading.service({ target:this.$refs.crud.$refs.table.$el })
      this.rolePage.pageSize = val
      this.fetchData(this.rolePage.pageNum)
    },
    handleCurrentChange(val) {
      this.loadingInstance = Loading.service({ target:this.$refs.crud.$refs.table.$el })
      this.rolePage.pageNum = val;
      this.fetchData(val)
    },
    //用户管理分页（子组件调用）
    handleUserSizeChange(val) {
      this.userPage.pageSize = val
      this.getUser(this.userPage.pageNum)
    },
    handleUserDataChange(val) {
      this.getUser(val)
      this.toggleSelection()
    },

    /**
     * 打开公司分配弹窗需要的接口
     *
     */
    getCompany() {
      selectCompany()
        .then((response) => {
          this.data = response.data
        })
        .catch(() => {
          this.$message({
            type: 'error',
            message: '公司查询失败!'
          })
        })
      console.log(this.data)
    },
    // 获取资源树
    getResourceTree() {
      const roleVo = this.$refs.crud.$refs.table.selection
      if (roleVo == null || roleVo.length === 0) {
        this.$message.error('至少选择一个角色进行操作')
        return
      }
      this.listLoading = true
      this.isReviewPerMission = false
      this.resourcedialogVisible = true
      const resourceQuery = {}
      resourceQuery.pageSize = 1000
      /**
       *  先查询到所有的资源构建出树
       */
      treeQuery(resourceQuery)
        .then((response) => {
          // this.resourceData = response.data
          console.log('response.data',response.data)
          this.resourceData = this.transform(response.data)
          for (let i = 0; i < roleVo.length; i++) {
            this.roleIdList.push(roleVo[i].id)
          }
          // 根据角色的id查询到角色所对应的资源进行打钩
          if (roleVo.length === 1) {
            this.fillResourceTree(roleVo[0].id)
          }
        })
        .finally(() => {
          this.listLoading = false
        })
    },
    // 用户拥有资源的回填
    fillResourceTree(roleId) {
      const resourceQuery = {}
      resourceQuery.pageSize = 1000
      resourceQuery.roleId = roleId
      treeQuery(resourceQuery)
        .then((res) => {
          console.log(res)
          for (let i = 0; i < res.data.length; i++) {
            this.$refs.tree.$refs.tree.setChecked(res.data[i].id, true, false)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    /***
     *  取得资源树的信息进行角色对应的资源的分配
     */
    assignResource() {
      const list = this.$refs.tree.$refs.tree.getCheckedNodes()
      const listParent = this.$refs.tree.$refs.tree.getHalfCheckedKeys()
      // const listParent = this.$refs.tree.data
      listParent.map((item) => {
        this.resourceIdList.push(item)
      })
      this.listLoading = true
      for (let i = 0; i < list.length; i++) {
        this.resourceIdList.push(list[i].id)
      }
      if (this.resourcedialogType === 'REVIEW') {
        this.resourcedialogType = ''
      } else {// 构建角色资源对象
        const roleResourceDTO = {
          roleIds: this.roleIdList,
          resourceIds: this.resourceIdList
        }
        console.log('roleResourceDTO',roleResourceDTO)
        // 请求后端接口
        assignResource(roleResourceDTO)
          .then((response) => {
            this.$message({
              message: '分配成功',
              type: 'success'
            })
            this.resourcedialogVisible = false
            this.resourceIdList = []
            this.roleIdList = []
            // 进行重新加载
            this.fetchData(this.rolePage.pageNum)
          })
          .catch(() => {
            this.$message({
              message: '分配失败',
              type: 'error'
            })
          }).finally(()=>{
               this.listLoading = false
          })

      }

    },
    // 增加角色
    addRole(roleDto) {
      this.adddialogVisible = false
      roleDto.version = '1'
      roleDto.createdBy = '2'
      roleDto.tenantId = '1'
      roleDto.companyId = '1'
      roleDto.orgId = '1337376369553833984'
      add(roleDto)
        .then((response) => {
          // 新增之后重新加载
          this.fetchData(this.rolePage.pageNum)
          this.$message({
            type: 'success',
            message: '添加成功!'
          })
          this.$router.push({
            path:'/centre/permission-manager/role',
          })
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 通过名字查询
    queryRoleByName() {
      this.rolePage.total = null
      this.rolePage.pages = null
      this.rolePage.pageNum = 1
      this.fetchData(this.rolePage.pageNum)
    },
    // 批量删除
    batchRemoveRole() {
      const roleVo = this.$refs.crud.$refs.table.selection
      if (roleVo == null || roleVo.length === 0) {
        this.$message.error('至少选择一条进行操作')
        return
      }
      const roleDtoS = new Array(roleVo.length)
      for (let i = 0; i < roleVo.length; i++) {
        // name: '',

        //   orgId: ''
        roleDtoS[i] = {
            name: roleVo[i].name || '0',
            code: roleVo[i].code || '0',
            remark: roleVo[i].remark || '0',
            // id: roleVo[i].id || '0',
            // status: roleVo[i].status || '0',
            // version: roleVo[i].version || '0',
            // created_by: roleVo[i].created_by || '0',
            // companyId: roleVo[i].companyId || '0',
            // tenantId: roleVo[i].tenantId || '0',
            // orgId: roleVo[i].orgId || '0'
          id: roleVo[i].id,
          version: roleVo[i].version
        }
      }
      console.log("批量删除",roleDtoS)
      if (roleDtoS.length !== 0) {
        this.$confirm('确定删除记录吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            batchRemove(roleDtoS).then((response) => {
              if(response.data.code == 200){
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
              }
              this.fetchData(1)
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      } else {
        this.$message({
          message: '请选择需要删除的数据',
          type: 'warning'
        })
      }
    },
    // 删除角色
    removeRole(row) {
      this.$confirm('确定删除记录吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          remove(row.id, row.version)
            .then((response) => {
              this.fetchData(1)
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            })
            .catch(() => {
              this.$message({
                type: 'error',
                message: '删除失败!'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    copyRole(row) {
      this.roleDto = {};
      this.dialogType = 'copy'
      this.updatedialogVisible = true
      queryRoleById(row.id)
        .then((res) => {
          this.roleDto = res
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 修改信息展示
    updateFromInfo(row) {
      this.roleDto = {}
      this.updatedialogVisible = true
      this.dialogType = 'update'
      queryRoleById(row.id)
        .then((res) => {
          this.roleDto = res
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 修改或编辑角色
    updateRole() {
      if (this.dialogType === 'update') {
        const roleVo = JSON.parse(JSON.stringify(this.roleDto))
        modify(roleVo)
          .then((response) => {
            console.log(response)
            // debugger
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            // 新增之后重新加载
            this.fetchData(this.rolePage.pageNum)
            // Just to simulate the time of the request
          })
          .catch(() => {
            this.$message({
              type: 'error',
              message: '修改失败!'
            })
          })
          .finally(() => {
            this.dialogType = ''
            this.roleVo = null
            this.updatedialogVisible = false
          })
      } else if (this.dialogType === 'copy') {
        this.roleDto.version = '1'
        this.roleDto.createdBy = '2'
        this.roleDto.tenantId = '1'
        this.roleDto.companyId = '1'
        this.roleDto.orgId = '1337376369553833984'
        const roleVo = JSON.parse(JSON.stringify(this.roleDto))
        add(roleVo)
          .then((response) => {
            // 新增之后重新加载
            this.fetchData(this.rolePage.pageNum)
            this.$message({
              type: 'success',
              message: '复制成功!'
            })
            // Just to simulate the time of the request
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)
          })
          .catch(() => {
            this.listLoading = false
          })
          .finally(() => {
            this.dialogType = ''
            this.updatedialogVisible = false
          })
      }
    },
    // 通过name查用户
    queryUserByName() {
      this.userPage.total = null
      this.userPage.pages = null
      this.userPage.pageNum = 1
      this.getUser(this.userPage.pageNum)
    },
    /**
     * 查询出系统用户
     * @param
     */
    getUser(pageNum) {
      this.listLoading = true
      this.userQuery.total = this.userPage.total
      this.userQuery.pageNum = pageNum
      this.userQuery.pageSize = this.userPage.pageSize
      commonQueryUser(this.userQuery)
        .then((response) => {
          const { total, pageNum, pageSize, pages } = response // 如果异常则被axios 的拦截器拦截并且显示错误码和消息
          this.userPage.total = parseInt(total)
          this.userPage.pages = parseInt(pages)
          this.userData = response.data
          // debugger
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 分配用户
    assignUser() {
      // 关闭弹窗
      const userVo = this.$refs.userTable.$refs.userTable.selection
      if (userVo == null || userVo.length === 0) {
        this.$message.error('至少选择一个用户进行操作')
        return
      }
      for (let i = 0; i < userVo.length; i++) {
        this.userIdList.push(userVo[i].id)
      }
      this.userdialogVisible = false
      console.log(this.roleIdList)
      const userRoleDTO = {
        roleIds: this.roleIdList,
        userIds: this.userIdList
      }
      assignUser(userRoleDTO)
        .then((response) => {
          this.$message({
            message: '分配成功',
            type: 'success'
          })
          this.userIdList = []
          this.roleIdList = []
          // 进行重新加载
          this.fetchData(1)
        })
        .catch(() => {
          this.$message({
            message: '分配失败',
            type: 'error'
          })
        })
        .finally(() => {
          this.selectionData = []
        })
    },
    // 取消用户分配
    cancelUser() {
      this.userdialogVisible = false
      this.selectionData = []
    },
    // 查询所有用户
    getUserAll() {
      const roleVo = this.$refs.crud.$refs.table.selection
      if (roleVo == null || roleVo.length === 0) {
        this.$message.error('至少选择一个角色进行操作')
        return
      }
      this.userdialogVisible = true
      for (let i = 0; i < roleVo.length; i++) {
        this.roleIdList.push(roleVo[i].id)
      }
      this.getUser(this.userPage.pageNum)
    },
    // 关闭弹窗
    handleClose() {
      this.adddialogVisible = false
      this.updatedialogVisible = false
      this.userdialogVisible = false
      this.resourcedialogVisible = false
      this.companydialogVisible = false
    },
    // eslint-disable-next-line no-dupe-keys,vue/no-dupe-keys
    refreshData() {
      this.loadingInstance = Loading.service({
        target:this.$refs.crud.$refs.table.$el
      });
      this.fetchData(this.rolePage.pageNum)
    },
    fetchData(pageNum) {
      this.listLoading = true
      this.roleQuery.total = this.rolePage.total
      this.roleQuery.pageNum = pageNum
      this.roleQuery.pageSize = this.rolePage.pageSize
      commonQuery(this.roleQuery)
        .then((response) => {
          const { total, pageNum, pageSize, pages } = response // 如果异常则被axios 的拦截器拦截并且显示错误码和消息
          this.rolePage.total = parseInt(total)
          this.rolePage.pages = parseInt(pages)
          this.tableData = response.data
          setTimeout(() => {
            this.listLoading = false
            this.loadingInstance.close()
          }, 1.5 * 1000)

          const roleName = this.$route.query.name
          // 点击角色跳转存在则选中
          if (roleName) {
            const tableDate = this.tableData.find(
              (item) => item.name === roleName
            )
            this.$nextTick(() => {
              this.$refs.crud.$refs.table.toggleRowSelection(tableDate, true)
            })
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 查看权限
    permission(row) {
      this.resourcedialogVisible = true
      this.resourcedialogType = 'REVIEW'
      this.isReviewPerMission = true
      const resourceQuery = {}
      resourceQuery.pageSize = 1000
      treeQuery(resourceQuery).then((response) => {
        // this.resourceData = response.data
        console.log(response.data)
        this.resourceData = this.transform(response.data)

        // 查看权限时，所有树节点全部禁用
        this.resourceData = this.disableTreeNode(this.resourceData)

        // this.roleIdList.push(row.id)
        this.fillResourceTree(row.id)
        // debugger
      })
    },

    // 禁用所有树节点
    disableTreeNode(data) {
      data.map((item) => {
        this.$set(item, "disabled", true)
        if (item.children && item.children.length > 0){
          item.children = this.disableTreeNode(item.children)
        }
      })
      return data
    },

    // 选择表格
    handleSelectionChange(selection, row) {
      const flag = selection.some((item) => {
        return item.id === row.id
      })
      const index = this.arrFindObjIndex(this.selectionData, row, 'id')
      if (!flag) {
        // selection中不包含row则是取消选中该行
        if (index !== -1) {
          this.selectionData.splice(index, 1)
        }
      } else {
        // selection中不包含row则是选中该行
        if (index === -1) {
          this.selectionData.push(row)
        }
      }
    },
    // 记忆选中表格的checkbox
    toggleSelection() {
      setTimeout(() => {
        this.userData.forEach((user) => {
          this.selectionData.forEach((selected) => {
            if (user.id === selected.id) {
              this.$refs.userTable.toggleRowSelection(user, true)
            }
          })
        })
      }, 500)
    },
    // 在一个对象数据中寻找某个对象的下标,通过key的值相等，判断数组中是否包含对象
    arrFindObjIndex(arr, obj, key) {
      let index = -1
      arr.forEach((item, idx) => {
        if (item[key] === obj[key]) {
          index = idx
        }
      })
      return index
    },
    // 获取所有公司信息
    getCompanyAll() {
      const roleVo = this.$refs.crud.$refs.table.selection
      if (roleVo == null || roleVo.length === 0) {
        this.$message.error('至少选择一个角色进行操作')
        return
      }
      this.companydialogVisible = true
      this.listLoading = true
      companyQuery({}).then(res => {
        this.companyData = res.data
        this.fillCompanyInfo(roleVo)
      })
      .catch(() => {
        this.$message.error('公司信息获取失败')
      })
      .finally(() => {
        this.listLoading = false
      })
    },
    // 将某一角色所属公司填充至table
    fillCompanyInfo(roleVo) {
      if (roleVo.length === 1) {
        // 获取角色对应的授权公司列表
        queryRoleCompany(roleVo[0].id).then(res => {
          const roleAuthCompanyIds = res.authCompanyIds  //授权公司列表
          if (roleAuthCompanyIds) {
            this.$nextTick(() => {
              // 遍历table的数据并进行判断
              this.companyData.forEach(company => {
                // 如果某一行的company_id在该角色对应的授权公司列表中，将其勾选
                if (roleAuthCompanyIds.indexOf(company.id) > -1) {
                  this.$refs.companyTable.$refs.companyTable.toggleRowSelection(company, true)
                }
              })
            })
          }
        })
        .catch(() => {
          this.$message.error("角色所属公司信息获取失败")
        })
      }
    },
    // 为角色分配公司
    assignCompany() {
      this.roleCompanyDTO.roleIds = this.$refs.crud.$refs.table.selection.map(role => role.id)
      this.roleCompanyDTO.authCompanyIds = this.$refs.companyTable.$refs.companyTable.selection.map(company => company.id)
      modifyRoleCompany(this.roleCompanyDTO)
      .then(res => {
        if (res) {
          this.cancelCompany()
          this.$message.success("角色所属公司分配成功")
        } else {
          this.$message.error("角色所属公司信息分配失败")
        }
      })
      .catch(() => {
        this.$message.error("角色所属公司信息分配失败")
      })
      .finally(() => {
        this.roleCompanyDTO.roleIds = []
        this.roleCompanyDTO.authCompanyIds = []
      })
    },
    cancelCompany() {
      this.companydialogVisible = false
    },
    handleRowSave(row,done,loading) {
      this.data.splice(0, 0, row);
      done();  // 关闭表单
      console.log("A",this.data)

      loading(); // 按钮停止加载
    },
    // 修改按钮
    handleRowUpdate(row,index,done,loading) {
      this.data.splice(index, 1, row);
      done();  // 关闭表单
      loading(); // 按钮停止加载
    },
    // 删除按钮
    rowDel(row, index) {
      this.$confirm('是否删除该条信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.data.splice(index, 1);
      });
    },
    handleEdit(row, index){
      this.$refs.crud.rowEdit(row, index);
    },
    getCellStyle(){
      return {'font-size':'14px'}
    }
  }
}
</script>

<style  scoped>
/deep/ .avue-crud__pagination {
  text-align: center;
  background-color: #f0f0f0;
}
/deep/ .avue-crud__header {
  margin-top: 10px;
  background-color: #f0f0f0;
}
/deep/ .avue-crud__body {
  background-color: #f0f0f0;
}
/deep/.labelClassName{
  font-size: 14px;
}

.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
.clearfix {
  &:after {
    visibility: hidden;
    display: block;
    font-size: 0;
    content: ' ';
    clear: both;
    height: 0;
  }
}
.box-card {
  height: 500px;
}

</style>
